#include"cross.h"
#include<stdio.h>
#include<malloc.h>
#include<time.h>
#include"mouse.h"
void printmap(int* puzzle, int height, int wide, int startx, int starty);
void reset(Mouse* m, Cross* c, int* puzzle, FILE* f);

int main(){
	Mouse* m = NULL;
	Cross* cross = NULL;
	int i = 0, j = 0;
	int startx = 0 , starty = 0;
	int height = 25, wide = 80;
	int way = 2;
	int end = 0;
	char c = 0;
	int* puzzle = NULL;
	FILE* f = fopen("map.txt","r");
	puzzle= (int*) malloc(sizeof(int)*wide*height);
	
	printf("If you want to start this program, press enter");
	scanf("%c", &c);

	if(f == NULL){
		reset(m,cross,puzzle,f);
		printf("there is no map.txt file\n");
		return -1;
	}

	fscanf(f,"%d, %d%c",&startx, &starty, &c);

	while(j >= 0){
        j=fgetc(f);
		if(j >= 48 && j <= 51){
			puzzle[i++] = j-48;
		}
	}
	close(f);
	printmap(puzzle, height, wide,startx, starty);
    Sleep(100);
	m = mkMouse(startx, starty, height, wide);
	cross = mkCross();			
    puzzle[startx+starty*(wide)]=1;
	while(end < 7){
		end = findway(m,puzzle,&way);
		if(end < 7){
			if(end == 0){
				way = pop(cross, &(m->x), &(m->y));
				way = (way+2)%4;
				if(way < 0){
					reset(m,cross,puzzle,f);
					printf("Pop error");
                    system("pause");
					return 0;
				}
			}else{
				if(end >1){
					if(push(cross, m->x, m->y, way) < 0){
						reset(m,cross,puzzle,f);
						printf("Push error");
						system("pause");
						return 0;
					}
				}
				move(m,puzzle,way);
			}
		}
		Sleep(50);
	}
	gotoxy(m->x,m->y);
	printf("M");
	gotoxy(1,26);
	printf("Mission Complete\n");		
	reset(m,cross,puzzle,f);	
	//printf("%d, %d\n",startx,starty);
    system("pause");
	return 0;

}		

void printmap(int* puzzle, int height, int wide, int startx, int starty){
	clrscr();
	int i = 0; 
    int j=0;
	for(i=0;i<height;i++){
		for(j=0;j < wide; j++){
            if(j+i*wide == startx+starty*wide){
                        printf("M");
            }
			else if(puzzle[j+i*wide] == 0){
				printf(" ");
			}
			else{
				printf("#");
			}
		}
	}
}
void reset(Mouse* m, Cross* c, int* puzzle, FILE* f){
	if(m != NULL){
		killMouse(m);
	}
	if(c != NULL){
		delCross(c);
	}
	if(puzzle != NULL){
		free(puzzle);
	}
	if(f != NULL){
		close(f);
	}
}
